<template>
  <div>
    <note-templates :data="stringData" :list="directory">
      <template #note>
        <h1>实现过程</h1>
        <div id="note-item1">
          <title-card title="调用"></title-card>
          <pre-code :code="code1" language="JavaScript" />
        </div>
        <div id="note-item2">
          <title-card title="websocket.js 完整代码"></title-card>
          <pre-code :code="code2" language="JavaScript" />
        </div>
        <div id="note-item3">
          <title-card title="./index.js 文件"></title-card>
          <pre-code :code="code3" language="JavaScript" />
        </div>
      </template>
    </note-templates>
  </div>
</template>

<script setup name="UniappWebSocket">
import NoteTemplates from '@/components/NoteTemplates/index.vue';
import TitleCard from '@/components/TitleCard/index.vue';
import { postArticleDetail } from '@/api/home.js';
import { onMounted, reactive, ref, toRefs } from 'vue';

const code1 = ref(`// index.vue
import WS from "@/utils/websocket.js"

export default {
//...
data() {
  return {
    ws: null
  }
},
onLoad() {
  this.ws && this.ws.closeSocket();
  this.ws = new WS(process.env.VUE_APP_WS_API+'/ws/xxx')  // xxx 表示接口地址URL
  
  // 发送数据
  // this.ws.webSocketSendMsg('发送信息')
  this.$nextTick(()=>{
    this.ws.getWebSocketMsg(data => {
      const dataJson = data;
      console.log('data', dataJson);
        if(typeof(dataJson) == "object") {
        console.log("wsObject", dataJson);
      }else {
        console.log(dataJson);
      }
    });
  })
},
beforeDestroy() {
  this.ws && this.ws.closeSocket();
  },
//...
}`);
const code2 = ref(`// @/utils/websocket.js
import { isJSON } from "./index"

class WebSocketClass {
  constructor(url) {
    this.lockReconnect = false;  // 是否开始重连
    this.wsUrl = "";  // ws 地址
    this.globalCallback = null;  // 回调方法
    this.userClose = false;  // 是否主动关闭
    this.createWebSocket(url);
  }

  createWebSocket(url) {
    // #ifdef H5
    if (typeof (WebSocket) === 'undefined') {
      this.writeToScreen("您的浏览器不支持WebSocket，无法获取数据");
      return false
    }
    // #endif

    // #ifdef APP-PLUS
    if (typeof (uni.connectSocket) === 'undefined') {
      this.writeToScreen("您的浏览器不支持WebSocket，无法获取数据");
      return false
    }
    // #endif

    this.wsUrl = url;
    try {
      // 创建一个this.ws对象【发送、接收、关闭socket都由这个对象操作】

      // #ifdef H5
      this.ws = new WebSocket(this.wsUrl);
      this.initEventHandle();
      // #endif

      // #ifdef APP-PLUS
      let that = this
      this.ws = uni.connectSocket({
        url: this.wsUrl,
        success(data) {
          console.log("websocket连接成功");
          
          that.initEventHandle();
        },
      });
      // #endif
    } catch (e) {
      this.reconnect(url);
    }
  }

  // 初始化
  initEventHandle() {
    /**
     * 监听WebSocket连接打开成功
     */

    // #ifdef H5
    this.ws.onopen = (event) => {
      console.log("WebSocket连接打开");
    };
    // #endif

    // #ifdef APP-PLUS
    this.ws.onOpen(res => {
      console.log('WebSocket连接打开'); 
    });
    // #endif

    
    /**
     * 连接关闭后的回调函数
     */

    // #ifdef H5
    this.ws.onclose = (event) => {
      if (!this.userClose) {
        this.reconnect(this.wsUrl); //重连
      }
    };
    // #endif

    // #ifdef APP-PLUS
    this.ws.onClose(() => {
      if (!this.userClose) {
        this.reconnect(this.wsUrl); //重连
      }
    });
    // #endif
    

    /**
     * 报错时的回调函数
     */ 

    // #ifdef H5
    this.ws.onerror = (event) => {
      if (!this.userClose) {
        this.reconnect(this.wsUrl); //重连
      }
    };
    // #endif

    // #ifdef APP-PLUS
    this.ws.onError(() => {
      if (!this.userClose) {
        this.reconnect(this.wsUrl); //重连
      }
    });
    // #endif


    /**
     * 收到服务器数据后的回调函数
     */ 
    
    // #ifdef H5
    this.ws.onmessage = (event) => {
      if(isJSON(event.data)) {
        const jsonobject = JSON.parse(event.data)
        
        this.globalCallback(jsonobject)
      }else {
        this.globalCallback(event.data)
      }
    };
    // #endif

    // #ifdef APP-PLUS
    this.ws.onMessage(event => {
      if(isJSON(event.data)) {
        const jsonobject = JSON.parse(event.data)

        this.globalCallback(jsonobject)
      }else {
        this.globalCallback(event.data)
      }
    });
    // #endif
  }

  // 关闭ws连接回调
  reconnect(url) {
    if (this.lockReconnect) return;
    this.ws.close();
    this.lockReconnect = true;  // 关闭重连，没连接上会一直重连，设置延迟避免请求过多
    setTimeout(() => {
      this.createWebSocket(url);
      this.lockReconnect = false;
    }, 1000);
  }

  // 发送信息方法
  webSocketSendMsg(msg) {
    this.ws && this.ws.send({
      data: msg,
      success() {
        console.log("消息发送成功");
      },
      fail(err) {
        console.log("关闭失败", err)
      }
    });
  }

  // 获取ws返回的数据方法
  getWebSocketMsg(callback) {
    this.globalCallback = callback
  }

  // 关闭ws方法
  closeSocket() {
    if (this.ws) {
      this.userClose = true;
      // #ifdef APP-PLUS
      this.ws.close({
        success(res) {
          console.log("关闭成功", res)
        },
        fail(err) {
          console.log("关闭失败", err)
        }
      });
      // #endif
      // #ifdef H5
      this.ws.close();
      // #endif
    }
  }

  writeToScreen(massage) {
    console.log(massage);
  }
}
export default WebSocketClass;`)
const code3 = ref(`// 判断字符串是否为JSON格式
export function isJSON(str) {
  if (typeof str == 'string') {
      try {
          var obj = JSON.parse(str);
          if (typeof obj == 'object' && obj) {
              return true;
          } else {
              return false;
          }

      } catch (e) {
          // console.log('error：'+str+'!!!'+e);
          return false;
      }
  }
  // console.log('It is not a string!')
}`)
const directory = ref([
  {
    name:'调用',
    id: 'note-item1'
  },
  {
    name:'websocket.js 完整代码',
    id: 'note-item2'
  },
  {
    name:'./index.js 文件',
    id: 'note-item3'
  }
]);

const data = reactive({
  stringData: {},
});
const { stringData } = toRefs(data);
const getTitle = () => {
  postArticleDetail({
    route: 'UniappWebSocket',
  }).then((res) => {
    stringData.value = res.data;
  });
};
onMounted(() => {
  getTitle();
});
</script>
